package com.heima.search.service.impl;

import com.heima.common.dto.ResponseResult;
import com.heima.search.dto.ApArticleSearchDto;
import com.heima.search.entity.ApAssociateWords;
import com.heima.search.repository.ApAssociateWordsRepository;
import com.heima.search.service.IApAssociateWordService;
import net.bytebuddy.asm.Advice;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ApAssociateWordServiceImpl implements IApAssociateWordService {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private ApAssociateWordsRepository apAssociateWordsRepository;

    @Override
    public ResponseResult search(ApArticleSearchDto dto) {
        if(dto==null|| StringUtils.isEmpty(dto.getSearchWords())||StringUtils.isEmpty(dto.getSearchWords().trim())){
            return ResponseResult.okResult();
        }
//        Query query=new Query();
//        query.addCriteria(Criteria.where("associateWords").regex("^"+dto.getSearchWords()+".*$"));
//        query.with(PageRequest.of(0,dto.getSize(), Sort.Direction.DESC,"createdTime"));
//        List<ApAssociateWords> words = mongoTemplate.find(query, ApAssociateWords.class);
        
        //根据用户传入的关键词在联想词表中进行查询
        Pageable page=PageRequest.of(0,dto.getSize(),Sort.Direction.DESC,"createdTime");
        List<ApAssociateWords> words = apAssociateWordsRepository.findByAssociateWordsStartingWith(dto.getSearchWords(), page);
        return ResponseResult.okResult(words);
    }
}
